﻿using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Diagnostics;
using Debug = UnityEngine.Debug;

/// <summary>
/// protobuf gen 自动化
/// </summary>
public class ProtobufBuild : Editor {

    static List<string> paths = new List<string>();
    static List<string> files = new List<string>();

    /// <summary>
    /// 数据目录
    /// </summary>
    static string AppDataPath
    {
        get { return Application.dataPath.ToLower(); }
    }

    /// <summary>
    /// 遍历目录及其子目录
    /// </summary>
    static void Recursive(string path)
    {
        string[] names = Directory.GetFiles(path);
        string[] dirs = Directory.GetDirectories(path);
        foreach (string filename in names)
        {
            string ext = Path.GetExtension(filename);
            if (ext.Equals(".meta")) continue;
            files.Add(filename.Replace('\\', '/'));
        }
        foreach (string dir in dirs)
        {
            paths.Add(dir.Replace('\\', '/'));
            Recursive(dir);
        }
    }

    [MenuItem("Protobuf/Build")]
    public static void BuildProtobufFile()
    {
        var root = Directory.GetParent(AppDataPath);
        string protogen = root + "/protogen-net/protogen.exe";

        string dir = AppDataPath + "/Scripts/proto";
        paths.Clear(); files.Clear(); Recursive(dir);

        foreach (string f in files)
        {
            string name = Path.GetFileName(f);
            string ext = Path.GetExtension(f);
            if (!ext.Equals(".proto"))
                continue;
            string outname = name.Replace(".proto",".cs");

            ProcessStartInfo info = new ProcessStartInfo();
            info.FileName = protogen;
            info.Arguments = " -i:" + name + " -o:" + outname;
            info.WindowStyle = ProcessWindowStyle.Hidden;
            info.UseShellExecute = true;
            info.WorkingDirectory = dir;
            info.ErrorDialog = true;
            Debug.LogWarning(info.FileName + " " + info.Arguments);

            Process pro = Process.Start(info);
            pro.WaitForExit();

            //赋值到服务器路径下
            string sourceFile = dir + "/" + outname;
            string destFile = root + "/Text1/Text1/Data/" + outname;
            Debug.LogWarning(sourceFile + " -> " + destFile);

            File.Copy(sourceFile, destFile, true);
        }
        AssetDatabase.Refresh();
    }
}
